<template>
  <div class="page-box">
    <!-- 筛区域 -->
    <div class="search-box">
      <!-- :inline="true" 表单在一行显示 -->
      <el-form size="mini" :inline="true" class="demo-form-inline">
        <el-form-item label="用户名">
          <el-input v-model.trim="query.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model.trim="query.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="query.sex" placeholder="请选择">
            <el-option
              value="男"
            />
            <el-option
              value="女"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="search">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 工具条区域 -->
    <div class="tabbar-box">
      <el-row type="flex" justify="space-between">
        <div>
          <el-button plain type="primary" icon="el-icon-plus" size="mini" @click="openDilog('add')">新增</el-button>
          <el-button plain type="warning" icon="el-icon-download" size="mini" @click="exportData">导出</el-button>
        </div>
        <div>
          <el-button icon="el-icon-arrow-down" size="mini" circle />
          <el-button icon="el-icon-refresh" size="mini" circle />
          <el-button icon="el-icon-menu" size="mini" circle />
        </div>
      </el-row>
    </div>
    <!-- 表格区域 -->
    <div class="table-box">
      <el-table
        :data="list"
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="#" width="50" />
        <el-table-column prop="id" label="用户ID" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="mobile" label="手机号" />
        <el-table-column label="用户头像">
          <template #default="{row}">
            <img style="width:50px;" :src="'http://124.223.14.236:8060/' + row.icon" alt="">
          </template>
        </el-table-column>
        <el-table-column prop="data" label="性别">
          <template #default="{row}">
            <el-tag v-if="row.sex===1" type="success">女</el-tag>
            <el-tag v-else>男</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="birthday" label="出生年月" />
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <el-row type="flex" justify="center">
              <el-button circle type="primary" icon="el-icon-edit" size="mini" @click="openDilog('edit',row.id)" />
              <el-button circle type="danger" icon="el-icon-delete" size="mini" @click="open(row.id)" />
            </el-row>
          </template>
        </el-table-column>

      </el-table>
    </div>
    <!-- 分页区域 -->
    <div class="page">
      <el-row type="flex" justify="end">
        <el-pagination
          background
          :current-page="query.page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="query.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>
    <!-- ! 弹层 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="handleClose"
    >
      <!-- ! 弹层中的表单 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small">
        <el-row type:flex justify="space-between">
          <el-col :span="12">
            <el-form-item label="用户名" style="width:300px" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" style="width:300px" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入手机号名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type:flex justify="space-between">
          <el-col :span="12">
            <el-form-item label="密码" style="width:300px" prop="password">
              <el-input v-model="form.password" :placeholder="placeholder" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别">
              <el-switch
                v-model="form.sex"
                :active-value="0"
                :inactive-value="1"
                active-text="男"
                inactive-text="女"
                @change="changeSex"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- ! 上传 -->
        <el-form-item label="用户头像">
          <el-upload
            ref="upload"
            v-model="form.icon"
            style="width:220px"
            class="upload-demo"
            action="http://124.223.14.236:8060/"
            :on-success="success"
            :file-list="fileList"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// ! 导出
import { exportData } from '@/utils/export'
import { getUserList, addUser, deleteUser, editUser, getUserDetail } from '@/api/user/user'
import { getImg } from '@/api/adv/img'
export default {
  data() {
    return {
      // ! 导出数据
      aoa: [],
      form: {
        icon: '',
        mobile: '',
        password: '',
        sex: '',
        username: ''
      }, rules: {
        mobile: [
          { required: true, message: '手机号类型必须', trigger: 'blur' }
        ],

        username: [
          { required: true, message: '用户名类型必须', trigger: 'blur' }
        ]
      },

      list: [],
      query: {
        sex: '',
        username: '',
        mobile: '',
        page: 1,
        limit: 10
      },
      options: [],
      value: '',
      total: 0,
      dialogVisible: false,
      dialogType: 'add',
      fileList: [],
      sexId: ''

    }
  },
  computed: {
    // ! 修改弹层标题
    dialogTitle() {
      let title = ''
      if (this.dialogType === 'add') title = '添加用户'
      if (this.dialogType === 'edit') title = '修改用户'
      return title
    },
    placeholder() {
      return this.form.id ? '留空表示不修改' : '请输入密码'
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // ! 搜索
    async search() {
      this.query.sex = this.query.sex === '男' ? '0' : '1'
      await this.initData()
      this.query.sex = this.query.sex === '0' ? '男' : '女'
    },
    // ! 重置
    reset() {
      this.query = {
        sex: '',
        username: '',
        mobile: '',
        page: 1,
        limit: 10
      }
      this.initData()
    },
    // ! 导出
    exportData() {
      this.list.forEach((item, index) => {
        this.aoa.push([index + 1, item.id, item.username, item.mobile, item.icon, item.sex ? '女' : '男', item.birthday])
      })
      exportData(this.list, ['#', '用户ID', '用户名', '手机号', '用户头像', '性别', '出生年月'], this.aoa)
    },
    // ! 上传图片
    async success(response, files, fileList) {
      const file = fileList[0].raw
      const fd = new FormData()
      fd.append('file', file)
      const res = await getImg(fd)
      this.form.icon = res.savePath
    },
    // ! 修改性别
    changeSex(value) {
      this.sexId = value ? '0' : '1'
    },
    async submit() {
      try {
        // ! 兜底校验
        await this.$refs.form.validate()
        // ! 添加
        if (this.dialogType === 'add') {
          this.form.sex = this.sexId
          await addUser(this.form)
          this.$message.success('添加成功!')
        }
        // ! 编辑
        if (this.dialogType === 'edit') {
          const { icon, mobile, password, sex, username, id } = this.form
          await editUser({
            icon, mobile, password, sex, username, id
          })
          this.$message.success('编辑成功!')
        }
        this.page = 1
        this.initData()
        this.handleClose()
      } catch (error) {
        console.log(error)
      }
    },
    // ! 删除
    open(id) {
      this.$confirm('确定删除吗,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // ! 删除请求
        await deleteUser(id)
        this.initData()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // ! 弹层打开
    async openDilog(type, id) {
      this.dialogType = type
      this.dialogVisible = true
      // ! 数据回显
      if (this.dialogType !== 'add') {
        const res = await getUserDetail(id)
        this.form = { ...res }
        // ! 图片回显
        const obj = { name: '点击查看详情', url: 'http://124.223.14.236:8060/' + res.icon }
        if (res.icon === null) {
          this.fileList = []
        } else {
          this.fileList.push(obj)
        }
      }
    },
    // ! 弹层关闭
    handleClose(done) {
      this.form = {
        icon: '',
        mobile: '',
        password: '',
        sex: '',
        username: ''
      }
      // ! 重置表单校验
      this.$refs.form.clearValidate()
      this.$refs.upload.clearFiles()
      this.fileList = []
      this.dialogVisible = false
    },
    handleSizeChange(value) {
      this.query.limit = value
      this.query.page = 1
      this.initData()
    },
    handleCurrentChange(value) {
      this.query.page = value
      this.initData()
    },
    async initData() {
      const res = await getUserList(this.query)
      this.list = res.data
      this.total = res.count
    }
  }
}
</script>
<style lang="scss" scoped>
  .page-box {
    margin: 20px;
    padding: 20px;
    background-color: #fff;
    .search-box,.tabbar-box {
      padding-top: 10px;
      height: 50px;
    }
  }
    ::v-deep .el-dialog__header{
   padding: 15px 20px 10px!important;
    border-bottom: 1px solid #e9ecef;
    background-color: #fafafa;
  }

</style>
